﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Microsoft.Win32;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using System.Net.Mail;
using System.Management;
using System.Web.Security;
using System.Threading;
using System.Text.RegularExpressions;
using System.Security.Cryptography; 

//using System.Runtime.Serialization;
//using Marketer;
//using System.Runtime.Serialization.Json;
//using System.Web.Script.Serialization;

namespace WindowsFormsApplication
{
    public partial class MainForm : Form
    {
        private bool REGISTERED = false;
        private int maxSender = 30;
        private string machineCode = string.Empty;
        private string authCode = string.Empty;
        List<string> keyWords = new List<string>();
        List<string> addWords = new List<string>();
        private int urlIndex = 0;
        List<string> urlList = new List<string>();
        List<string> engineDict = new List<string>();
        //Dictionary<string, string> engineDict = new Dictionary<string, string>();
        public bool DocumentCompleted = false;
        List<string> MailAddress_AGENT = new List<string>();
        List<string> MailAddress_ALL = new List<string>();

        string smtpServer = "";
        string smtpMailAdd = "";
        string smtpPassword = "";

        string smtpServer2 = "";
        string smtpMailAdd2 = "";
        string smtpPassword2 = "";

        string paperSubject = "";
        string paperContent = "";

        public MainForm()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
        }

        private void mainForm_Load(object sender, EventArgs e)
        {
            machineCode = get_harddisk_serial();
            machineCode_textBox.Text = machineCode;
            authCode = DCB031(MD5(machineCode));
            REGISTERED = judge_regidit();
            load_all_cfg();
        }

        private void load_all_cfg()
        {
            system_label.Text = "操作系统: " + getSystemInfo();
            load_mailCfg();
            load_softpaper();

        }

        #region start
        private void start_button_Click(object sender, EventArgs e)
        {
            //清理
            urlIndex = 0;
            engineDict.Clear();
            keyWords.Clear();
            urlList.Clear();
            engineDict.Clear();
            MailAddress_AGENT.Clear();
            MailAddress_ALL.Clear();
            processBar_label.Text = "0%";
            progressBar.Value = 0;

            //获取及构造
            get_engines();
            get_keyword();
            buildSearchCommand();
            

            if (engineDict.Count == 0)
            {
                MessageBox.Show("至少需要选择一个搜索引擎", "系统提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                tabControl1.SelectedIndex = 1;
            }
            else if (keyWords.Count == 0)
            {
                MessageBox.Show("至少需要填写一个特征词", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                tabControl1.SelectedIndex = 1;
            }
            else if (smtpServer == "" || smtpMailAdd == "" || smtpPassword == "")
            {
                MessageBox.Show("邮件配置信息不完整！", "系统提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                tabControl1.SelectedIndex = 2;
            }
            else if (paperSubject == "" || paperContent == "")
            {
                MessageBox.Show("软文信息不完整！", "系统提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                tabControl1.SelectedIndex = 3;
            }
            else
            {
                logger_list(" ---- 欢迎使用邮件营销系统！ ---- ");
                if (!REGISTERED)
                {
                    logger_list("未注册版本，最多使用 " + 2.ToString() + " 个特征词！");
                    logger_list("未注册版本，最多发送 " + maxSender.ToString() + " 封邮件！");
                }
                if (backgroundWorker1.IsBusy != true)
                {
                    backgroundWorker1.RunWorkerAsync();// 启动异步操作
                }
                start_button.Enabled = false;
            }

            //start_button.Enabled = false;
            //string url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=abc";
            //url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=led%20%E8%81%94%E7%B3%BB%20mail";
            //string codeType = "utf-8";
            //string mailer = getMailFromSearch(1, "led");
            //log_listBox.Items.Add(mailer);
            //send_mail_smtp("qq.com", "test056", "yiqian2012", "jin.tao@arrisi.com", "标量1", "真正发mail的用户不在这里设定，这个仅仅只做显示用");
        }
        private void cancel_button_Click(object sender, EventArgs e)
        {
            logger_list("取消任务");
            cancel_button.Enabled = false;
            if (backgroundWorker1.WorkerSupportsCancellation == true)
            {
                // 取消异步操作
                backgroundWorker1.CancelAsync();
            }
        }
        #endregion

        #region mailCfg
        private void write_mailCfg1()
        {
            string Current = Directory.GetCurrentDirectory();//获取当前根目录
            Ini ini = new Ini(Current + "/configuration.ini");
            smtpServer = smtp_server_comboBox.Text;
            smtpMailAdd = smtp_mailadd_textBox.Text;
            smtpPassword = smtp_password_textBox.Text;

            ini.Write("SMTP", "server", smtpServer);
            ini.Write("SMTP", "mailadd", smtpMailAdd);
            ini.Write("SMTP", "password", smtpPassword);
        }

        private void write_mailCfg2()
        {
            string Current = Directory.GetCurrentDirectory();//获取当前根目录
            Ini ini = new Ini(Current + "/configuration.ini");

            smtpServer2 = comboBox_smtp_server2.Text;
            smtpMailAdd2 = textBox_smtp_account2.Text;
            smtpPassword2 = textBox_smtp_password2.Text;

            ini.Write("SMTP2", "server", smtpServer2);
            ini.Write("SMTP2", "mailadd", smtpMailAdd2);
            ini.Write("SMTP2", "password", smtpPassword2);
        }
        private void load_mailCfg()
        {
            string currentPath = Directory.GetCurrentDirectory();//获取当前根目录
            Ini ini = new Ini(currentPath + "/configuration.ini");
            smtpServer = ini.ReadValue("SMTP", "server");
            smtpMailAdd = ini.ReadValue("SMTP", "mailadd");
            smtpPassword = ini.ReadValue("SMTP", "password");

            smtpServer2 = ini.ReadValue("SMTP2", "server");
            smtpMailAdd2 = ini.ReadValue("SMTP2", "mailadd");
            smtpPassword2 = ini.ReadValue("SMTP2", "password");

            smtp_server_comboBox.Text = smtpServer;
            smtp_mailadd_textBox.Text = smtpMailAdd;
            smtp_password_textBox.Text = smtpPassword;

            comboBox_smtp_server2.Text = smtpServer2;
            textBox_smtp_account2.Text = smtpMailAdd2;
            textBox_smtp_password2.Text = smtpPassword2;

        }
        #endregion

        #region smtp
        private bool send_mail_smtp(string smtpServer, string frommail, string password, string[] mailNames, string subject, string content)
        {
            try
            {
                string account = frommail.Substring(0, frommail.IndexOf("@"));
                MailAddress from = new MailAddress(frommail, ""); //邮件的发件人
                MailMessage mail = new MailMessage();
                //设置邮件的标题
                mail.Subject = subject;
                //设置邮件的发件人
                //Pass:如果不想显示自己的邮箱地址，这里可以填符合mail格式的任意名称，真正发mail的用户不在这里设定，这个仅仅只做显示用
                mail.From = from;
                //设置邮件的收件人
                string address = "";
                string displayName = "";
                /*  这里这样写是因为可能发给多个联系人，每个地址用 ; 号隔开
                  一般从地址簿中直接选择联系人的时候格式都会是 ：用户名1 < mail1 >; 用户名2 < mail 2>; 
                  因此就有了下面一段逻辑不太好的代码
                  如果永远都只需要发给一个收件人那么就简单了 mail.To.Add("收件人mail");
                */

                //to2 = "jin.tao@arrisi.com";
                //string[] mailNames = tolist.Split(';');
                foreach (string name in mailNames)
                {
                    if (name != string.Empty)
                    {
                        if (name.IndexOf('<') > 0)
                        {
                            displayName = name.Substring(0, name.IndexOf('<'));
                            address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
                        }
                        else
                        {
                            displayName = string.Empty;
                            address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
                        }
                        mail.To.Add(new MailAddress(address, displayName));
                    }
                }

                //设置邮件的抄送收件人
                //这个就简单多了，如果不想快点下岗重要文件还是CC一份给领导比较好
                //mail.CC.Add(new MailAddress("txw1958@163.com", "尊敬的领导"));
                //mail.Bcc.Add(new MailAddress("jin.tao@arrisi.com", ""));

                //设置邮件的内容
                mail.Body = content;
                //设置邮件的格式
                mail.BodyEncoding = System.Text.Encoding.UTF8;
                mail.IsBodyHtml = true;
                //设置邮件的发送级别
                mail.Priority = MailPriority.Normal;

                ////设置邮件的附件，将在客户端选择的附件先上传到服务器保存一个，然后加入到mail中
                //string fileName = txtUpFile.PostedFile.FileName.Trim();
                //fileName = "D:/UpFile/" + fileName.Substring(fileName.LastIndexOf("/") + 1);
                //txtUpFile.PostedFile.SaveAs(fileName); // 将文件保存至服务器
                //mail.Attachments.Add(new Attachment(fileName));

                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;

                SmtpClient client = new SmtpClient();
                //设置用于 SMTP 事务的主机的名称，填IP地址也可以了
                client.Host = smtpServer;
                //设置用于 SMTP 事务的端口，默认的是 25
                //client.Port = 25;
                client.UseDefaultCredentials = false;
                //这里才是真正的邮箱登陆名和密码，比如我的邮箱地址是 hbgx@hotmail， 我的用户名为 hbgx ，我的密码是 xgbh
                client.Credentials = new NetworkCredential(account, password);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                //都定义完了，正式发送了，很是简单吧！
                client.Send(mail);
            }
            catch (Exception e)
            {
                string error = e.Message;
                return false;
                //throw;
            }
            return true;
        }
        private void smtp_save_button_Click(object sender, EventArgs e)
        {
            if (smtp_server_comboBox.Text == "" || smtp_mailadd_textBox.Text == "" || smtp_password_textBox.Text == "")
            {
                MessageBox.Show("邮件配置没有填写完整", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                write_mailCfg1();
                smtp_save_button.Enabled = false;
            }
        }
        private void button_smtp2_save_Click(object sender, EventArgs e)
        {
            if (comboBox_smtp_server2.Text == "" || textBox_smtp_account2.Text == "" || textBox_smtp_password2.Text == "")
            {
                MessageBox.Show("邮件2配置没有填写完整", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                write_mailCfg2();
                button_smtp2_save.Enabled = false;
            }
        }
        private void button_smtptest_Click(object sender, EventArgs e)
        {
            if (smtp_server_comboBox.Text == "" || smtp_mailadd_textBox.Text == "" || smtp_password_textBox.Text == "")
            {
                MessageBox.Show("主SMTP配置没有填写完整", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                smtp_save_button.Enabled = true;
            }
            else if (comboBox_smtp_server2.Text == "" || textBox_smtp_account2.Text == "" || textBox_smtp_password2.Text == "")
            {
                MessageBox.Show("次SMTP配置没有填写完整", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                button_smtp2_save.Enabled = true;
            }
            else if (softPaperTitle_textBox.Text == "" || textBox_softPaperContent.Text == "")
            {
                MessageBox.Show("软文广告没有填写完整", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            else if (textBox_smtptest_to.Text == "")
            {
                MessageBox.Show("收件人没有填写", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                string[] toList = new string[1];
                toList[0] = textBox_smtptest_to.Text.ToString();
                bool sended1 = send_mail_smtp(smtpServer, smtpMailAdd, smtpPassword, toList, softPaperTitle_textBox.Text, textBox_softPaperContent.Text);
                if (sended1 == false)
                {
                    MessageBox.Show("请检查主SMTP、账号及密码填写是否正确\r\n并且确认邮件服务正常使用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    smtp_save_button.Enabled = true;
                }
                else
                {
                    MessageBox.Show("主SMTP邮件发送成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                bool sended2 = send_mail_smtp(smtpServer2, smtpMailAdd2, smtpMailAdd2, toList, softPaperTitle_textBox.Text, textBox_softPaperContent.Text);
                if (sended2 == false)
                {
                    MessageBox.Show("请检查次SMTP、账号及密码填写是否正确\r\n并且确认邮件服务能正常使用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    button_smtp2_save.Enabled = true;
                }
                else
                {
                    MessageBox.Show("次SMTP邮件发送成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        #endregion

        #region softpaper
        private void saveSoftPaper_button_Click(object sender, EventArgs e)
        {
            if (softPaperTitle_textBox.Text == "" || textBox_softPaperContent.Text == "")
            {
                 MessageBox.Show("软文广告没有填写完整", "系统提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
            else
            {
                write_softpaper();
                saveSoftPaper_button.Enabled = false;
            }

        }
        private void write_softpaper()
        {
            paperSubject = softPaperTitle_textBox.Text;
            paperContent = textBox_softPaperContent.Text;
            string currentPath = Directory.GetCurrentDirectory();//获取当前根目录
            Ini ini = new Ini(currentPath + "/configuration.ini");
            ini.Write("softpaper1", "subject", paperSubject);

            //创建一个文件流，用以写入或者创建一个StreamWriter
            FileStream fs = new FileStream(currentPath + "/softpaper.txt", FileMode.Create, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.Flush();
            // 使用StreamWriter来往文件中写入内容
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);
            // 把richTextBox1中的内容写入文件
            m_streamWriter.Write(textBox_softPaperContent.Text);
            //关闭此文件
            m_streamWriter.Flush();
            m_streamWriter.Close();

        }
        private void load_softpaper()
        {
            string currentPath = Directory.GetCurrentDirectory();//获取当前根目录
            Ini ini = new Ini(currentPath + "/configuration.ini");
            paperSubject = ini.ReadValue("softpaper1", "subject");
            //paperContent = ini.ReadValue("softpaper1", "content");
            softPaperTitle_textBox.Text = paperSubject;
            //softPaperContent_richTextBox.Text = content;

            FileStream fs = new FileStream(currentPath + "/softpaper.txt", FileMode.OpenOrCreate, FileAccess.Read);
            StreamReader m_streamReader = new StreamReader(fs);
            //使用StreamReader类来读取文件
            m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
            // 从数据流中读取每一行，直到文件的最后一行，并在richTextBox1中显示出内容
            this.textBox_softPaperContent.Text = "";
            string strLine = m_streamReader.ReadLine();
            while (strLine != null)
            {
                this.textBox_softPaperContent.Text += strLine + "\n";
                strLine = m_streamReader.ReadLine();
            }
            //关闭此StreamReader对象
            m_streamReader.Close();
            paperContent = textBox_softPaperContent.Text;
        }


        #endregion

        #region search
        private void get_keyword()
        {
            if (tzc1_textBox.Text!= "")
            {
                keyWords.Add(tzc1_textBox.Text);
            }
            if (tzc2_textBox.Text != "")
            {
                keyWords.Add(tzc2_textBox.Text);
            }
            if (tzc3_textBox.Text != "")
            {
                keyWords.Add(tzc3_textBox.Text);
            }
            if (tzc4_textBox.Text != "")
            {
                keyWords.Add(tzc4_textBox.Text);
            }
            if (tzc5_textBox.Text != "")
            {
                keyWords.Add(tzc5_textBox.Text);
            }
            if (tzc6_textBox.Text != "")
            {
                keyWords.Add(tzc6_textBox.Text);
            }
            if (tzc7_textBox.Text != "")
            {
                keyWords.Add(tzc7_textBox.Text);
            }
            if (tzc8_textBox.Text != "")
            {
                keyWords.Add(tzc8_textBox.Text);
            }
            if (tzc9_textBox.Text != "")
            {
                keyWords.Add(tzc9_textBox.Text);
            }
            if (tzc0_textBox.Text != "")
            {
                keyWords.Add(tzc0_textBox.Text);
            }
            //return keywords;
        }
        private void get_engines()
        {
            //google baidu yahoo bing soso youdao
            if (google_checkBox.Checked == true)
            {
                engineDict.Add("http://www.google.com.hk/search?q=");
            }
            if (baidu_checkBox.Checked == true)
            {
                engineDict.Add("http://www.baidu.com/s?wd=");
            }
            if (yahoo_checkBox.Checked == true)
            {
                engineDict.Add("http://search.cn.yahoo.com/search?p=");
            }
            if (bing_checkBox.Checked == true)
            {
                engineDict.Add("http://cn.bing.com/search?q=");
            }
            if (soso_checkBox.Checked == true)
            {
                engineDict.Add("http://www.soso.com/q?w=");
            }
            if (youdao_checkBox.Checked == true)
            {
                engineDict.Add("http://www.youdao.com/search?q=");
            }
        }
        public void buildSearchCommand()
        {
            //#email "@"  email + @
            //#mailto '@'
            //#邮箱 "@"
            //#邮件地址 "@"
            //#联系方式 '@'
            addWords.Add("email @");
            addWords.Add("mailto @");
            addWords.Add("邮箱 @");
            addWords.Add("邮件地址 @");
            addWords.Add("联系方式 @");

            //abc 
            //http://www.baidu.com/s?wd=abc&pn=10&ie=utf-8
            //http://www.baidu.com/s?wd=abc&pn=0&ie=utf-8
            //http://www.baidu.com/s?wd=abc&pn=10&ie=utf-8
            //http://www.baidu.com/s?wd=abc&pn=20&ie=utf-8

            //你好
            //UrlEncode编码 %E4%BD%A0%E5%A5%BD
            //http://www.baidu.com/s?wd=%E4%BD%A0%E5%A5%BD&pn=0&ie=utf-8
            //http://www.baidu.com/s?wd=%E4%BD%A0%E5%A5%BD&pn=10&ie=utf-8
            //http://www.baidu.com/s?wd=%E4%BD%A0%E5%A5%BD&pn=20&ie=utf-8

            for (int i = 0; i < keyWords.Count; i++) //确定长度的list 前缀 关键词
            {
                for (int j = 0; j < addWords.Count; j++) //确定长度的后缀
                {
                    string keywordAll = UrlEncode(keyWords[i] + " " + addWords[i]);
                    for (int pIndex = 0; pIndex < 20; pIndex++)
                    {
                        for (int eIndex = 0; eIndex < engineDict.Count; eIndex++)
                        {
                            string surl = "";
                            if (pIndex == 0)
                            {
                                surl = engineDict[eIndex] + keywordAll + "&ie=utf-8";
                                
                            }
                            else
                            {
                                if (engineDict[eIndex].Contains("baidu"))
                                {
                                    surl = engineDict[eIndex] + keywordAll + "&pn=" + ((pIndex) * 10).ToString() + "&ie=utf-8";
                                }
                                if (engineDict[eIndex].Contains("google"))
                                {
                                    surl = engineDict[eIndex] + keywordAll + "&start=" + ((pIndex) * 10).ToString();
                                }
                                if (engineDict[eIndex].Contains("yahoo"))
                                {
                                    surl = engineDict[eIndex] + keywordAll + "&page=" + (pIndex + 1).ToString();
                                }
                                if (engineDict[eIndex].Contains("bing"))
                                {
                                    surl = engineDict[eIndex] + keywordAll + "&first=" + ((pIndex + 1) * 10 - 9).ToString();
                                }
                            }
                            if (surl != "")
                            {
                                urlList.Add(surl); 
                            }
                            
                        }
                    }
                }
            }
        }
        public static string UrlEncode(string str)
        {
            return System.Web.HttpUtility.UrlEncode(str);
        }
        public string getMailFromSearch(int engine, string keyword)
        {
            //construct url
            string cUrl = string.Empty;
            string codeType = "";
            switch (engine)
            {
                case 1:
                    //http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=abc
                    cUrl = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + keyword + " 联系 mail";
                    codeType = "utf-8";
                    break;
                default:
                    break;
            }

            //catch the result from search
            string result = "";
            WebRequest wReq = WebRequest.Create(cUrl);
            WebResponse wResp = wReq.GetResponse();
            Stream respStream = wResp.GetResponseStream();
            using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(codeType)))
            {
                result = reader.ReadToEnd();
            }

            JsonReader reader2 = new JsonTextReader(new StringReader(result));

            List<string> mails = new List<string>();
            while (reader2.Read())
            {
                //log_listBox.Items.Add("not null -" + reader2.TokenType + "++" + reader2.ValueType + "xx" + reader2.Value);
                if (reader2.Value != null && reader2.Value.ToString().Contains("@"))
                {
                    //log_listBox.Items.Add(reader2.TokenType + "++" + reader2.ValueType + "xx" + reader2.Value);
                    log_listBox.Items.Add(reader2.Value);

                    mails.Add(reader2.Value.ToString());
                }
            }


            //catch the mail from result and conver to string
            return result;
        }

        #endregion

        #region register/authcode
        private bool judge_regidit()
        {
            bool register = false;
            if ((read_regidit() == authCode) && (authCode != ""))
            {
                haveRegistered_label.Text = "已注册, 感谢您的使用";
                buyAuthCode_linkLabel.Text = "";
                
                machineCode_label1.Visible = false;
                machineCode_textBox.Visible = false;
                registerCode_label.Visible = false;
                registerCode_textBox.Visible = false;
                registe_button.Visible = false;
                register = true;
            }
            if (register)
            {
                tzc0_textBox.Enabled = true;
                tzc9_textBox.Enabled = true;
                tzc8_textBox.Enabled = true;
                tzc7_textBox.Enabled = true;
                tzc6_textBox.Enabled = true;
                tzc5_textBox.Enabled = true;
                tzc4_textBox.Enabled = true;
                tzc3_textBox.Enabled = true;
                tzc2_textBox.Enabled = true;
            }
            else
            {
                tzc0_textBox.Enabled = false;
                tzc9_textBox.Enabled = false;
                tzc8_textBox.Enabled = false;
                tzc7_textBox.Enabled = false;
                tzc6_textBox.Enabled = false;
                tzc5_textBox.Enabled = false;
                tzc4_textBox.Enabled = false;
                tzc3_textBox.Enabled = false;
                //tzc2_textBox.Enabled = false;
            }
                  
            return register;
        }
        private string read_regidit()
        {
            string regInfo = "";
            try
            {
                RegistryKey myreg = Registry.LocalMachine.OpenSubKey("software\\Doucube");
                regInfo = myreg.GetValue("MailMarketer").ToString();
                myreg.Close();
            }
            catch (Exception)
            {
                regInfo = "";
                //throw;
            }
            return regInfo;

        }
        private void write_regidit(string value)
        {
            RegistryKey key = Registry.LocalMachine;
            RegistryKey createDcbKey = key.CreateSubKey("software\\Doucube");
            RegistryKey writeDcbKey = key.OpenSubKey("software\\Doucube", true); //该项必须已存在
            writeDcbKey.SetValue("MailMarketer", value, RegistryValueKind.String);
            //在HKEY_LOCAL_MACHINE\SOFTWARE\test下创建一个名为“test”，值为“博客园”的键值。如果该键值原本已经存在，则会修改替换原来的键值，如果不存在则是创建该键值。
            // 注意：SetValue()还有第三个参数，主要是用于设置键值的类型，如：字符串，二进制，Dword等等~~默认是字符串。如：
            // software.SetValue("test", "0", RegistryValueKind.DWord); //二进制信息
            key.Close();

        }
        private string get_harddisk_serial()
        {
            string HDid = "";
            ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection moc = cimobject.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                HDid = (string)mo.Properties["Model"].Value;
                machineCode = HDid;
                //MessageBox.Show(HDid);
                return HDid;
                
            }
            return "获取机器码出错!";
 



        }
        private void registe_button_Click(object sender, EventArgs e)
        {
            write_regidit(authCode);
            judge_regidit();
        }
        private void buyAuthCode_linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.buyAuthCode_linkLabel.LinkVisited = true;
            System.Diagnostics.Process.Start("http://shop36833901.taobao.com/");
        }
        public string SHA1(string source)
        {
            //string sha1code = (source == "") ? (FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1")) : "";
            return (source != "") ? (FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1")) : "";
            
        }
        public string MD5(string source)
        {
            //return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5"); ;
            return (source != "") ? (FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5")) : "";
        }
        #region 算法2 DES
        public static string KEY_64 = "tvbzn9i7";//注意了，是8个字符，64位    
        public static string IV_64 = "iv640017";//注意了，是8个字符，64位
        //public static string IV_64 = "tvbzn9i7";//注意了，是8个字符，64位
        /// <summary>
        /// 加密的方法，通过2个密匙进行加密
        /// </summary>
        /// <param name="data">通过Md5加密一次</param>
        /// <param name="KEY_64"></param>
        /// <param name="IV_64"></param>
        /// <returns></returns>
        public static string DESEncrypt(string data, string KEY_64, string IV_64)
        {
            if (data == "" || data == string.Empty || data == null)
            {
                return "DESEncrypt(): data is null";
            }
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }
        /// <summary>
        /// 解密的方法（）
        /// </summary>
        /// <param name="data"></param>
        /// <param name="KEY_64"></param>
        /// <param name="IV_64"></param>
        /// <returns></returns>
        public static string DESDecrypt(string data, string KEY_64, string IV_64)
        {
            if (data == "" || data == string.Empty || data == null)
            {
                return "DESEncrypt(): data is null";
            }

            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }
        #endregion
        public string DCB031(string source)
        { 
            //List<string> mList = new List<string>();
            //for (int i = 0; i < source.Length; i+=3)
            //{
            //    string x = "";
            //    x = source.Substring (i, 1);
            //    mList.Add(x);
            //}
            //string line = string.Join("", mList.ToArray());

            //return line;
            string dcb031Encrypt = DESEncrypt(machineCode, "abcd0031", IV_64);
            if (dcb031Encrypt.Length < 25)
            {
                return dcb031Encrypt;
            }
            else
            {
                return dcb031Encrypt.Substring(0, 25);
            }
        }
        #endregion

        #region system
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.linkLabel1.LinkVisited = true;
            // Navigate to a URL.
            System.Diagnostics.Process.Start("http://www.doucube.com");
        }

        private string getSystemInfo()
        {
            string system_os = "Microsoft ";
            // Get OperatingSystem information from the system namespace.
            System.OperatingSystem osInfo = System.Environment.OSVersion;
            switch (osInfo.Platform)
            {
                case System.PlatformID.Win32Windows:
                    switch (osInfo.Version.Minor)
                    {
                        case 0:
                            system_os = "Microsoft Windows 95";
                            break;
                        case 10:
                            if (osInfo.Version.Revision.ToString() == "2222A")
                                system_os = "Microsoft Windows 98 Second Edition";
                            else
                                system_os = "Microsoft Windows 98";
                            break;
                        case 90:
                            system_os = "Microsoft Windows Me";
                            break;
                        default:
                            system_os = "未知版本:" + osInfo.Version.Minor.ToString();
                            break;
                    }
                    break;

                // Platform is Windows NT 3.51, Windows NT 4.0, Windows 2000,
                // or Windows XP.
                case System.PlatformID.Win32NT:
                    switch (osInfo.Version.Major)
                    {
                        case 3:
                            system_os = "Microsoft Windows NT 3.51";
                            break;
                        case 4:
                            system_os = "Microsoft Windows NT 4.0";
                            break;
                        case 5:
                            if (osInfo.Version.Minor == 0)
                                system_os = "Microsoft Windows 2000";
                            else
                                system_os = "Microsoft Windows XP";
                            break;
                        case 6:
                            system_os = "Microsoft Windows 7";
                            break;
                        default:
                            system_os = "未知版本:" + osInfo.Version.Major.ToString() + "-" + osInfo.Version.Minor.ToString();
                            break;
                    }
                    break;
            }
            return system_os;
        }

        #endregion

        #region backgroundworker
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                processBar_label.Text = "取消!";
                //start_button.Enabled = true;
            }
            else if (e.Error != null)
            {
                processBar_label.Text = "错误: " + e.Error.Message;
            }
            else
            {
                processBar_label.Text = "完成!";
                start_button.Enabled = true;
            }

        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            processBar_label.Text = (e.ProgressPercentage).ToString() + "%";
            progressBar.Value = Convert.ToInt32(e.ProgressPercentage);

        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (urlIndex = 1; urlIndex <= urlList.Count; urlIndex++)
            {
                //logger_list("提交请求： " + (i + 1).ToString());
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    Random ro = new Random();
                    this.webBrowser1.Navigate(urlList[urlIndex]);
                    int cTime = 0;
                    DocumentCompleted = false;
                    while (true)
                    {
                        if (cTime > 5 || DocumentCompleted)
                        {
                            break;
                        }
                        Thread.Sleep(ro.Next(4000, 8000));    // 等待响应
                        cTime += 1;
                    }
                    Thread.Sleep(ro.Next(10000, 15000));
                }
                double process = (Convert.ToDouble(urlIndex) / urlList.Count) * 100.0;
                worker.ReportProgress(Convert.ToInt32(Math.Round(process, MidpointRounding.AwayFromZero)));
            }
        }
        #endregion

        #region webbrowser
        private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            {
                //logger_all("Loading " + this.webBrowser1.Url.AbsoluteUri);
            }
            else
            {
                logger_all("开始分析第 " + urlIndex.ToString() + " 个页面，共 " + urlList.Count.ToString() + " 页. ");
                //logger_all("Loading " + this.webBrowser1.Url.AbsoluteUri + " Complete!");
                DocumentCompleted = true;
                StreamReader sr = new StreamReader(this.webBrowser1.DocumentStream, Encoding.GetEncoding("gb2312"));
                string proxyHtml = sr.ReadToEnd();
                if (this.webBrowser1.Url.AbsoluteUri.Contains("baidu"))
                {
                    sendEmailFromString_baidu(proxyHtml);
                }
            }
        }
        private void sendEmailFromString_baidu(string htmlSource)
        {
            MailAddress_AGENT.Clear();
            //  <tr><td>.+?</td></tr>
            //  [a-zA-Z0-9]+[a-zA-Z0-9-_.]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+  电子邮件地址
            string patternSplit = "</td></tr>";
            //string patternProxy = "<tr><td>((\\d+\\.){3}\\d+)</td><td>(\\d{2,5})</td><td>(.+?)</td><td>(\\w+)</td><td><div\\sclass=\"addr_style\">(.+?)</div>";
            string patternMail = "[a-zA-Z0-9]+[a-zA-Z0-9-_.]+@[a-zA-Z0-9._-]+\\.[a-zA-Z]+";
            string[] arrayProxy = Regex.Split(htmlSource, patternSplit, RegexOptions.IgnoreCase);
            //Regex r = new Regex(patternProxy);
            //  
            foreach (string iSplitString in arrayProxy)
            {
                string iSplitString_Agent = Regex.Replace(iSplitString, "<font.+?>|</font>", "", RegexOptions.IgnoreCase);
                MatchCollection mc = Regex.Matches(iSplitString_Agent, patternMail, RegexOptions.IgnoreCase);
                foreach (var item in mc)
                {
                    MailAddress_AGENT.Add(item.ToString());
                    MailAddress_ALL.Add(item.ToString());
                }
            }

            //去重复
            for (int i = 0; i < MailAddress_AGENT.Count; i++)
            {
                for (int j = i + 1; j < MailAddress_AGENT.Count; j++)
                {
                    if (MailAddress_AGENT[i].Equals(MailAddress_AGENT[j]))
                        MailAddress_AGENT.Remove(MailAddress_AGENT[j]);
                }
            }

            logger_all("本次获得 " + MailAddress_AGENT.Count.ToString() + " 个邮件地址, 总共获得 " + MailAddress_ALL.Count.ToString() + " 个邮件地址");
            if (MailAddress_AGENT.Count > 0)
            {
                
                for (int i = 0; i < MailAddress_AGENT.Count; i++)
                {
                    logger_all(MailAddress_AGENT[i].ToString());
                }
                //发送邮件
                string[] addList = MailAddress_AGENT.ToArray();
                bool sended1 = send_mail_smtp(smtpServer, smtpMailAdd, smtpPassword, addList, paperSubject, paperContent);
                if (sended1 == true)
                {
                    logger_all("邮件发送成功！");
                }
                else
                {
                    logger_all("Error: 主SMTP发送失败！");
                    logger_all("请检查主SMTP、账号及密码填写是否正确并且确认邮件服务正常使用！");
                    logger_all("尝试使用次SMTP发送");
                    if (comboBox_smtp_server2.Text == "" || textBox_smtp_account2.Text == "" || textBox_smtp_password2.Text == "")
                    {
                        logger_all("次SMTP信息不完整!");
                    }
                    else
                    {
                        bool sended2 = send_mail_smtp(smtpServer2, smtpMailAdd2, smtpPassword2, addList, paperSubject, paperContent);
                        if (sended2 == false)
                        {
                            logger_all("Error: 次SMTP发送失败！");
                            logger_all("请检查次SMTP、账号及密码填写是否正确并且确认邮件服务正常使用！");
                        }
                        else
                        {
                            logger_all("邮件发送成功！");
                        }
                    }

                }
            }
            if (!REGISTERED)
            {
                if (MailAddress_ALL.Count >= maxSender)
                {
                    logger_list("未注册版本，最多发送 " + maxSender.ToString() + " 封邮件！");
                    backgroundWorker1.CancelAsync();
                }
               
            }
        }
        #endregion

        #region record
        private void logger_list(string content)
        {
            DateTime currentTime = DateTime.Now;
            string current_record = currentTime.ToString("T") + " " + content;
            log_listBox.Items.Add(current_record);
            log_listBox.TopIndex = this.log_listBox.Items.Count - (int)(this.log_listBox.Height / this.log_listBox.ItemHeight);
        }
        private void logger_file(string content)
        {
            string fname = "logfile.txt";
            FileInfo finfo = new FileInfo(fname);
            if (finfo.Exists && finfo.Length > 512000)
            {
                finfo.Delete();
            }
            using (FileStream fs = finfo.OpenWrite())
            {
                DateTime currentTime = DateTime.Now;
                string current_record = currentTime.ToString("T") + " " + content;
                StreamWriter w = new StreamWriter(fs);
                w.BaseStream.Seek(0, SeekOrigin.End);//设置写数据流的起始位置为文件流的末尾  
                w.Write(current_record + "\r\n");  //写入日志内容并换行  
                w.Flush();
                w.Close();  //关闭写数据流  
            }
        }
        public void logger_all(string log)
        {
            logger_list(log);
            logger_file(log);
        }
        #endregion

        #region datagridview
        private void dataGridView_smtp_cfg_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridView dw = (DataGridView)sender;
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dw.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            dw.RowHeadersDefaultCellStyle.Font, rectangle,
            dw.RowHeadersDefaultCellStyle.ForeColor,
            TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            //int index = 1;
            //DataGridViewRow row = dataGridView_smtp_cfg.Rows[index];
            //row.Cells["Result"].Value = "Pass";
        }
        #endregion





    }

    public class Ini
    {
        // 声明INI文件的写操作函数 WritePrivateProfileString()
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        // 声明INI文件的读操作函数 GetPrivateProfileString()
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);

        private string sPath = null;
        public Ini(string path)
        {
            this.sPath = path;
        }
        public void Write(string section, string key, string value)
        {
            // section=配置节，key=键名，value=键值，path=路径
            WritePrivateProfileString(section, key, value, sPath);
        }
        public string ReadValue(string section, string key)
        {
            // 每次从ini中读取多少字节
            System.Text.StringBuilder temp = new System.Text.StringBuilder(65535);
            // section=配置节，key=键名，temp=上面，path=路径
            GetPrivateProfileString(section, key, "", temp, 65535, sPath);
            return temp.ToString();
        }

    }
}
